//! # 调试命令
//!
//! 用于调试运行中的服务，提供监控、日志、性能分析等功能

use crate::config::CliConfig;
use crate::error::{CliError, CliResult};
use clap::Args;
use colored::*;
use console::Emoji;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::process::Stdio;
use std::time::{Duration, SystemTime};
use tokio::fs;
use tokio::process::Command;
use tokio::time::sleep;
use tracing::{info, warn};

static BUG: Emoji<'_, '_> = Emoji("🐛 ", "");
static CHART: Emoji<'_, '_> = Emoji("📊 ", "");
static SEARCH: Emoji<'_, '_> = Emoji("🔍 ", "");
static GEAR: Emoji<'_, '_> = Emoji("⚙️ ", "");
static CHECK: Emoji<'_, '_> = Emoji("✅ ", "");

/// 调试命令参数
#[derive(Args, Debug)]
pub struct DebugArgs {
    /// 服务名称
    pub service: Option<String>,

    /// 显示日志
    #[arg(long)]
    pub logs: bool,

    /// 显示指标
    #[arg(long)]
    pub metrics: bool,

    /// 性能分析
    #[arg(long)]
    pub profile: bool,

    /// 链路追踪
    #[arg(long)]
    pub trace: bool,

    /// 健康检查
    #[arg(long)]
    pub health: bool,

    /// 实时监控
    #[arg(long)]
    pub monitor: bool,

    /// 跟踪日志（实时）
    #[arg(short, long)]
    pub follow: bool,

    /// 日志行数
    #[arg(long, default_value = "100")]
    pub lines: u32,

    /// 监控间隔（秒）
    #[arg(long, default_value = "5")]
    pub interval: u64,
}

/// 服务状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceStatus {
    /// 服务名称
    pub name: String,
    /// 状态
    pub status: ServiceState,
    /// 端口
    pub port: Option<u16>,
    /// PID
    pub pid: Option<u32>,
    /// 内存使用
    pub memory_usage: Option<u64>,
    /// CPU 使用率
    pub cpu_usage: Option<f64>,
    /// 运行时间
    pub uptime: Option<Duration>,
}

/// 服务状态
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ServiceState {
    /// 运行中
    Running,
    /// 已停止
    Stopped,
    /// 错误
    Error,
    /// 未知
    Unknown,
}

/// 服务指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceMetrics {
    /// 请求数
    pub request_count: u64,
    /// 平均响应时间
    pub avg_response_time: f64,
    /// 错误数
    pub error_count: u64,
    /// 并发连接数
    pub active_connections: u32,
    /// 内存使用
    pub memory_usage: u64,
    /// CPU 使用率
    pub cpu_usage: f64,
}

/// 执行调试命令
pub async fn execute(args: DebugArgs, _config: CliConfig) -> CliResult<()> {
    println!("{} {}开始调试工具", BUG, "调试".bright_green().bold());

    // 如果没有指定具体操作，显示服务状态的概览
    if !args.logs && !args.metrics && !args.profile && !args.trace && !args.health && !args.monitor {
        show_service_overview(&args).await?
    } else {
        // 执行具体的调试操作
        if args.health {
            check_service_health(&args).await?;
        }
        if args.logs {
            show_service_logs(&args).await?;
        }
        if args.metrics {
            show_service_metrics(&args).await?;
        }
        if args.profile {
            analyze_service_performance(&args).await?;
        }
        if args.trace {
            show_trace_analysis(&args).await?;
        }
        if args.monitor {
            start_real_time_monitoring(&args).await?;
        }
    }

    Ok(())
}

// =============================================================================
// 调试功能实现
// =============================================================================

/// 显示服务概览
async fn show_service_overview(args: &DebugArgs) -> CliResult<()> {
    info!("获取服务概览");
    println!("{} 服务状态概览", SEARCH);
    println!();

    let services = discover_services(args).await?;
    
    if services.is_empty() {
        println!("🚨 未发现运行中的服务");
        return Ok(());
    }

    // 显示表头
    println!("{:<20} {:<10} {:<8} {:<10} {:<10} {:<15}", 
        "服务名称".bright_blue().bold(),
        "状态".bright_blue().bold(),
        "端口".bright_blue().bold(),
        "PID".bright_blue().bold(),
        "CPU %".bright_blue().bold(),
        "内存(MB)".bright_blue().bold()
    );
    println!("{}", "-".repeat(80).bright_black());

    // 显示服务信息
    for service in &services {
        let status_color = match service.status {
            ServiceState::Running => "running".bright_green(),
            ServiceState::Stopped => "stopped".bright_red(),
            ServiceState::Error => "error".bright_red(),
            ServiceState::Unknown => "unknown".bright_yellow(),
        };

        println!("{:<20} {:<10} {:<8} {:<10} {:<10} {:<15}",
            service.name.bright_white(),
            status_color,
            service.port.map_or("-".to_string(), |p| p.to_string()),
            service.pid.map_or("-".to_string(), |p| p.to_string()),
            service.cpu_usage.map_or("-".to_string(), |c| format!("{:.1}", c)),
            service.memory_usage.map_or("-".to_string(), |m| format!("{:.1}", m as f64 / 1024.0 / 1024.0))
        );
    }

    println!();
    println!("📝 使用方法:");
    println!("  查看日志: {}", "rustcloud debug <service> --logs".bright_blue());
    println!("  查看指标: {}", "rustcloud debug <service> --metrics".bright_blue());
    println!("  健康检查: {}", "rustcloud debug <service> --health".bright_blue());
    println!("  实时监控: {}", "rustcloud debug <service> --monitor".bright_blue());

    Ok(())
}

/// 发现服务
async fn discover_services(args: &DebugArgs) -> CliResult<Vec<ServiceStatus>> {
    let mut services = Vec::new();

    if let Some(service_name) = &args.service {
        // 获取指定服务的状态
        if let Ok(status) = get_service_status(service_name).await {
            services.push(status);
        }
    } else {
        // 自动发现本地服务
        services.extend(discover_local_services().await?);
        services.extend(discover_docker_services().await?);
        services.extend(discover_kubernetes_services().await?);
    }

    Ok(services)
}

/// 获取服务状态
async fn get_service_status(service_name: &str) -> CliResult<ServiceStatus> {
    // 先尝试从进程中查找
    if let Ok(status) = get_process_status(service_name).await {
        return Ok(status);
    }

    // 尝试从 Docker 中查找
    if let Ok(status) = get_docker_service_status(service_name).await {
        return Ok(status);
    }

    // 尝试从 Kubernetes 中查找
    if let Ok(status) = get_k8s_service_status(service_name).await {
        return Ok(status);
    }

    Ok(ServiceStatus {
        name: service_name.to_string(),
        status: ServiceState::Unknown,
        port: None,
        pid: None,
        memory_usage: None,
        cpu_usage: None,
        uptime: None,
    })
}

/// 发现本地服务
async fn discover_local_services() -> CliResult<Vec<ServiceStatus>> {
    let mut services = Vec::new();
    
    // 查找运行中的 Rust 进程
    let output = Command::new("ps")
        .args(["aux"])
        .output()
        .await?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.contains("target/release/") || line.contains("target/debug/") {
                if let Ok(status) = parse_process_line(line).await {
                    services.push(status);
                }
            }
        }
    }

    Ok(services)
}

/// 发现 Docker 服务
async fn discover_docker_services() -> CliResult<Vec<ServiceStatus>> {
    let mut services = Vec::new();
    
    let output = Command::new("docker")
        .args(["ps", "--format", "table {{.Names}}\t{{.Status}}\t{{.Ports}}"])
        .output()
        .await;

    if let Ok(output) = output {
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines().skip(1) { // 跳过标题行
                if let Ok(status) = parse_docker_line(line).await {
                    services.push(status);
                }
            }
        }
    }

    Ok(services)
}

/// 发现 Kubernetes 服务
async fn discover_kubernetes_services() -> CliResult<Vec<ServiceStatus>> {
    let mut services = Vec::new();
    
    let output = Command::new("kubectl")
        .args(["get", "pods", "-o", "wide"])
        .output()
        .await;

    if let Ok(output) = output {
        if output.status.success() {
            let stdout = String::from_utf8_lossy(&output.stdout);
            for line in stdout.lines().skip(1) { // 跳过标题行
                if let Ok(status) = parse_k8s_line(line).await {
                    services.push(status);
                }
            }
        }
    }

    Ok(services)
}

/// 检查服务健康状态
async fn check_service_health(args: &DebugArgs) -> CliResult<()> {
    println!("{} 健康检查", CHART);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    let status = get_service_status(service_name).await?;
    
    println!("  服务名称: {}", status.name.bright_blue());
    println!("  运行状态: {}", match status.status {
        ServiceState::Running => "✅ 运行中".bright_green(),
        ServiceState::Stopped => "❌ 已停止".bright_red(),
        ServiceState::Error => "⚠️ 错误".bright_red(),
        ServiceState::Unknown => "❓ 未知".bright_yellow(),
    });

    if let Some(port) = status.port {
        // 检查端口可达性
        println!("  端口检查: {}", check_port_health(port).await?);
        
        // 检查 HTTP 健康端点
        println!("  HTTP 检查: {}", check_http_health(port).await?);
    }

    if let Some(pid) = status.pid {
        println!("  进程 ID: {}", pid.to_string().bright_cyan());
    }

    if let Some(memory) = status.memory_usage {
        println!("  内存使用: {:.1} MB", memory as f64 / 1024.0 / 1024.0);
    }

    if let Some(cpu) = status.cpu_usage {
        println!("  CPU 使用: {:.1}%", cpu);
    }

    Ok(())
}

/// 显示服务日志
async fn show_service_logs(args: &DebugArgs) -> CliResult<()> {
    println!("{} 服务日志", SEARCH);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    // 尝试从不同源获取日志
    if try_show_local_logs(service_name, args).await.is_ok() {
        return Ok(());
    }

    if try_show_docker_logs(service_name, args).await.is_ok() {
        return Ok(());
    }

    if try_show_k8s_logs(service_name, args).await.is_ok() {
        return Ok(());
    }

    println!("⚠️ 未能找到服务 {} 的日志", service_name.bright_yellow());
    Ok(())
}

/// 显示服务指标
async fn show_service_metrics(args: &DebugArgs) -> CliResult<()> {
    println!("{} 服务指标", CHART);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    let metrics = get_service_metrics(service_name).await?;
    
    println!("  请求数: {}", metrics.request_count.to_string().bright_green());
    println!("  平均响应时间: {:.2} ms", metrics.avg_response_time);
    println!("  错误数: {}", metrics.error_count.to_string().bright_red());
    println!("  活跃连接: {}", metrics.active_connections.to_string().bright_blue());
    println!("  内存使用: {:.1} MB", metrics.memory_usage as f64 / 1024.0 / 1024.0);
    println!("  CPU 使用: {:.1}%", metrics.cpu_usage);

    // 显示性能趋势图
    show_performance_chart(&metrics).await?;

    Ok(())
}

/// 分析服务性能
async fn analyze_service_performance(args: &DebugArgs) -> CliResult<()> {
    println!("{} 性能分析", GEAR);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    println!("正在分析服务 {} 的性能...", service_name.bright_blue());
    
    // 收集性能数据
    let mut samples = Vec::new();
    for i in 0..10 {
        println!("收集样本 {} / 10...", i + 1);
        let metrics = get_service_metrics(service_name).await?;
        samples.push(metrics);
        sleep(Duration::from_secs(1)).await;
    }
    
    // 分析数据
    let avg_response_time: f64 = samples.iter().map(|s| s.avg_response_time).sum::<f64>() / samples.len() as f64;
    let max_response_time = samples.iter().map(|s| s.avg_response_time).fold(0.0, f64::max);
    let min_response_time = samples.iter().map(|s| s.avg_response_time).fold(f64::INFINITY, f64::min);
    
    let avg_cpu = samples.iter().map(|s| s.cpu_usage).sum::<f64>() / samples.len() as f64;
    let max_cpu = samples.iter().map(|s| s.cpu_usage).fold(0.0, f64::max);
    
    let avg_memory = samples.iter().map(|s| s.memory_usage).sum::<u64>() / samples.len() as u64;
    let max_memory = samples.iter().map(|s| s.memory_usage).max().unwrap_or(0);
    
    println!();
    println!("📊 性能分析结果:");
    println!("  响应时间:");
    println!("    平均: {:.2} ms", avg_response_time);
    println!("    最大: {:.2} ms", max_response_time);
    println!("    最小: {:.2} ms", min_response_time);
    println!("  CPU 使用:");
    println!("    平均: {:.1}%", avg_cpu);
    println!("    峰值: {:.1}%", max_cpu);
    println!("  内存使用:");
    println!("    平均: {:.1} MB", avg_memory as f64 / 1024.0 / 1024.0);
    println!("    峰值: {:.1} MB", max_memory as f64 / 1024.0 / 1024.0);
    
    // 性能建议
    println!();
    println!("💡 性能建议:");
    if avg_response_time > 1000.0 {
        println!("  ⚠️ 响应时间过长，建议检查数据库查询和网络延迟");
    }
    if avg_cpu > 80.0 {
        println!("  ⚠️ CPU 使用率过高，建议优化算法或增加实例");
    }
    if avg_memory > 512 * 1024 * 1024 {
        println!("  ⚠️ 内存使用过多，建议检查内存泄漏");
    }
    
    Ok(())
}

/// 显示链路追踪
async fn show_trace_analysis(args: &DebugArgs) -> CliResult<()> {
    println!("{} 链路追踪", SEARCH);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    println!("正在分析服务 {} 的调用链路...", service_name.bright_blue());
    
    // 模拟链路追踪数据
    println!();
    println!("🔍 调用链路分析:");
    println!("  服务入口: {} -> 响应时间: 245ms", service_name.bright_blue());
    println!("    ┣ 数据库查询 -> 响应时间: 156ms");
    println!("    ┣ 外部 API 调用 -> 响应时间: 89ms");
    println!("    ┗ 缓存操作 -> 响应时间: 12ms");
    
    println!();
    println!("🔥 热点分析:");
    println!("  最慢操作: 数据库查询 (63.7% 时间)");
    println!("  优化建议: 增加数据库索引，使用连接池");
    
    Ok(())
}

/// 开始实时监控
async fn start_real_time_monitoring(args: &DebugArgs) -> CliResult<()> {
    println!("{} 实时监控", CHART);
    
    let service_name = args.service.as_ref().ok_or_else(|| {
        CliError::validation("请指定服务名称")
    })?;

    println!("开始监控服务 {} (按 Ctrl+C 停止)...", service_name.bright_blue());
    println!();
    
    // 显示标题
    println!("{:<12} {:<8} {:<10} {:<12} {:<8} {:<12}", 
        "时间".bright_blue().bold(),
        "CPU %".bright_blue().bold(),
        "内存(MB)".bright_blue().bold(),
        "请求/秒".bright_blue().bold(),
        "错误".bright_blue().bold(),
        "响应时间".bright_blue().bold()
    );
    println!("{}", "-".repeat(70).bright_black());
    
    // 实时监控循环
    let mut last_request_count = 0;
    loop {
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .unwrap();
        let time_str = format!("{:02}:{:02}:{:02}", 
            (now.as_secs() / 3600) % 24,
            (now.as_secs() / 60) % 60,
            now.as_secs() % 60
        );
        
        if let Ok(metrics) = get_service_metrics(service_name).await {
            let requests_per_sec = if last_request_count > 0 {
                (metrics.request_count.saturating_sub(last_request_count)) / args.interval
            } else {
                0
            };
            last_request_count = metrics.request_count;
            
            let cpu_color = if metrics.cpu_usage > 80.0 {
                metrics.cpu_usage.to_string().bright_red()
            } else if metrics.cpu_usage > 60.0 {
                metrics.cpu_usage.to_string().bright_yellow()
            } else {
                metrics.cpu_usage.to_string().bright_green()
            };
            
            println!("{:<12} {:<8} {:<10.1} {:<12} {:<8} {:<12.2}",
                time_str,
                format!("{:.1}", cpu_color),
                metrics.memory_usage as f64 / 1024.0 / 1024.0,
                requests_per_sec,
                metrics.error_count,
                metrics.avg_response_time
            );
        } else {
            println!("{:<12} {:<8} {:<10} {:<12} {:<8} {:<12}",
                time_str, "-", "-", "-", "-", "-"
            );
        }
        
        sleep(Duration::from_secs(args.interval)).await;
    }
}

// =============================================================================
// 辅助函数
// =============================================================================

/// 获取进程状态
async fn get_process_status(service_name: &str) -> CliResult<ServiceStatus> {
    let output = Command::new("ps")
        .args(["aux"])
        .output()
        .await?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        for line in stdout.lines() {
            if line.contains(service_name) {
                return parse_process_line(line).await;
            }
        }
    }
    
    Err(CliError::general("未找到进程"))
}

/// 获取 Docker 服务状态
async fn get_docker_service_status(service_name: &str) -> CliResult<ServiceStatus> {
    let output = Command::new("docker")
        .args(["ps", "--filter", &format!("name={}", service_name), "--format", "{{.Names}}\t{{.Status}}\t{{.Ports}}"])
        .output()
        .await?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        if let Some(line) = stdout.lines().next() {
            return parse_docker_line(line).await;
        }
    }
    
    Err(CliError::general("未找到 Docker 容器"))
}

/// 获取 Kubernetes 服务状态
async fn get_k8s_service_status(service_name: &str) -> CliResult<ServiceStatus> {
    let output = Command::new("kubectl")
        .args(["get", "pods", "-l", &format!("app={}", service_name), "-o", "wide"])
        .output()
        .await?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        if let Some(line) = stdout.lines().skip(1).next() {
            return parse_k8s_line(line).await;
        }
    }
    
    Err(CliError::general("未找到 Kubernetes Pod"))
}

/// 解析进程行
async fn parse_process_line(line: &str) -> CliResult<ServiceStatus> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() >= 11 {
        let pid: u32 = parts[1].parse().unwrap_or(0);
        let cpu: f64 = parts[2].parse().unwrap_or(0.0);
        let memory_kb: u64 = parts[5].parse().unwrap_or(0) * 1024; // KB to bytes
        let name = parts[10].split('/').last().unwrap_or("unknown").to_string();
        
        return Ok(ServiceStatus {
            name,
            status: ServiceState::Running,
            port: None, // 需要额外检测
            pid: Some(pid),
            memory_usage: Some(memory_kb),
            cpu_usage: Some(cpu),
            uptime: None,
        });
    }
    
    Err(CliError::general("无法解析进程信息"))
}

/// 解析 Docker 行
async fn parse_docker_line(line: &str) -> CliResult<ServiceStatus> {
    let parts: Vec<&str> = line.split('\t').collect();
    if parts.len() >= 3 {
        let name = parts[0].to_string();
        let status = if parts[1].contains("Up") {
            ServiceState::Running
        } else {
            ServiceState::Stopped
        };
        
        // 解析端口
        let port = if parts[2].contains(":") {
            parts[2].split(':').next()
                .and_then(|p| p.parse().ok())
        } else {
            None
        };
        
        return Ok(ServiceStatus {
            name,
            status,
            port,
            pid: None,
            memory_usage: None,
            cpu_usage: None,
            uptime: None,
        });
    }
    
    Err(CliError::general("无法解析 Docker 信息"))
}

/// 解析 Kubernetes 行
async fn parse_k8s_line(line: &str) -> CliResult<ServiceStatus> {
    let parts: Vec<&str> = line.split_whitespace().collect();
    if parts.len() >= 5 {
        let name = parts[0].to_string();
        let status = match parts[2] {
            "Running" => ServiceState::Running,
            "Pending" | "ContainerCreating" => ServiceState::Unknown,
            _ => ServiceState::Error,
        };
        
        return Ok(ServiceStatus {
            name,
            status,
            port: None,
            pid: None,
            memory_usage: None,
            cpu_usage: None,
            uptime: None,
        });
    }
    
    Err(CliError::general("无法解析 Kubernetes 信息"))
}

/// 检查端口健康
async fn check_port_health(port: u16) -> CliResult<colored::ColoredString> {
    let output = Command::new("nc")
        .args(["-z", "localhost", &port.to_string()])
        .output()
        .await;
    
    match output {
        Ok(output) if output.status.success() => Ok("✅ 可达".bright_green()),
        _ => Ok("❌ 不可达".bright_red()),
    }
}

/// 检查 HTTP 健康
async fn check_http_health(port: u16) -> CliResult<colored::ColoredString> {
    let client = reqwest::Client::new();
    let url = format!("http://localhost:{}/health", port);
    
    match client.get(&url).timeout(Duration::from_secs(5)).send().await {
        Ok(response) if response.status().is_success() => Ok("✅ 健康".bright_green()),
        Ok(_) => Ok("⚠️ 异常".bright_yellow()),
        Err(_) => Ok("❌ 无响应".bright_red()),
    }
}

/// 尝试显示本地日志
async fn try_show_local_logs(service_name: &str, args: &DebugArgs) -> CliResult<()> {
    let log_paths = [
        format!("logs/{}.log", service_name),
        format!("/var/log/{}.log", service_name),
        format!("/tmp/{}.log", service_name),
    ];
    
    for log_path in &log_paths {
        if std::path::Path::new(log_path).exists() {
            let mut cmd = Command::new("tail");
            cmd.arg("-n").arg(args.lines.to_string());
            
            if args.follow {
                cmd.arg("-f");
            }
            
            cmd.arg(log_path);
            
            let output = cmd.output().await?;
            if output.status.success() {
                println!("{}", String::from_utf8_lossy(&output.stdout));
                return Ok(());
            }
        }
    }
    
    Err(CliError::general("未找到日志文件"))
}

/// 尝试显示 Docker 日志
async fn try_show_docker_logs(service_name: &str, args: &DebugArgs) -> CliResult<()> {
    let mut cmd = Command::new("docker");
    cmd.arg("logs");
    
    if args.follow {
        cmd.arg("-f");
    }
    
    cmd.arg("--tail").arg(args.lines.to_string());
    cmd.arg(service_name);
    
    let output = cmd.output().await?;
    if output.status.success() {
        println!("{}", String::from_utf8_lossy(&output.stdout));
        Ok(())
    } else {
        Err(CliError::general("获取 Docker 日志失败"))
    }
}

/// 尝试显示 Kubernetes 日志
async fn try_show_k8s_logs(service_name: &str, args: &DebugArgs) -> CliResult<()> {
    let mut cmd = Command::new("kubectl");
    cmd.arg("logs");
    
    if args.follow {
        cmd.arg("-f");
    }
    
    cmd.arg("--tail").arg(args.lines.to_string());
    cmd.arg(format!("deployment/{}", service_name));
    
    let output = cmd.output().await?;
    if output.status.success() {
        println!("{}", String::from_utf8_lossy(&output.stdout));
        Ok(())
    } else {
        Err(CliError::general("获取 Kubernetes 日志失败"))
    }
}

/// 获取服务指标
async fn get_service_metrics(service_name: &str) -> CliResult<ServiceMetrics> {
    // 模拟指标数据（实际实现中应从 Prometheus 或其他监控系统获取）
    let _ = service_name; // 避免警告
    
    Ok(ServiceMetrics {
        request_count: 1234,
        avg_response_time: 125.5,
        error_count: 3,
        active_connections: 42,
        memory_usage: 256 * 1024 * 1024, // 256MB
        cpu_usage: 35.2,
    })
}

/// 显示性能图表
async fn show_performance_chart(_metrics: &ServiceMetrics) -> CliResult<()> {
    println!();
    println!("📊 性能趋势 (最近 24 小时):");
    println!("  CPU:    ▄▄▆█▆▄▂▃▅▇█▆▄▂▁▂▄▆█▇▅▃▂▁");
    println!("  内存:   ▂▃▅▆▇██▇▆▅▄▃▂▁▂▄▆▇█▇▆▄▃▂");
    println!("  请求:   ▁▂▄▆█▇▅▃▂▄▆█▇▅▃▁▂▄▇█▆▄▂");
    Ok(())
}